<template>
  <view class="page">
    <view class="container">
      
      <!-- 业务员区域 -->
      <view v-if="isBusiness">
        <!-- 标题 -->
        <view class="title">分配号码</view>
        <!-- <view style="height: -80rpx;"></view> -->

        <!-- 分配表单 -->
        <!-- <view v-if="showForm" class="form-group">
          <view class="form-item item-id">
            <text class="label">工号：</text>
            <input
              class="input"
              type="text"
              placeholder="工号"
              :value="employeeId"
              @input="onEmployeeIdInput"
            />
          </view>
          <view class="form-item item-level">
            <text class="label">级别：</text>
            <picker
              mode="selector"
              :range="levelOptions"
              @change="onLevelChange"
            >
              <view class="picker">{{ level || '级别' }}</view>
            </picker>
          </view>
          <button class="submit-btn item-btn" @click="assignNumber">
            分配号码
          </button>
        </view> -->

        <!-- —— 恢复原来那块 "大号号码卡片" —— -->
        <view class="number-card">
          <view class="day-number">{{ displayNumber || '无' }}</view>
        </view>

        <!-- —— 恢复原来那块 "信息卡片" —— -->
        <view class="info-card">
          <view class="remarks">{{ displayRemark || '暂无备注' }}</view>
          <view class="info-line">艺名：{{ userName || '—' }}</view>
          <view class="info-line">工号：{{ displayEmployeeId || '—' }}</view>
          <view class="info-line">级别：{{ displayLevel || '—' }}</view>
         
        </view>

        <!-- 在这里加上业务员扫码分配号码按钮及功能 -->
        <view class="scan-section">
          <button class="scan-btn cu-btn block bg-white lg round" @click="scanAssignQrCode">
            扫码分配号码
          </button>
        </view>

        <!-- 时间信息 -->
        <view class="bottom-info">
          <view class="circle-container" @click="handleClick">
            <image
              src="/static/refresh.png"
              :class="['circle-icon', isClicked ? 'active' : '']"
            />
          </view>
          <view class="time-info">
            <text class="weekday">{{ weekday }}</text>
            <text class="clock">{{ currentTime }}</text>
          </view>
        </view>
      </view>

      <!-- 非业务员扫码 -->
      <view v-else class="scanner-section">
        <view class="title">扫码打卡</view>
        <button class="scan-btn cu-btn block bg-blue lg round" @click="scanQrCode">
          扫一扫
        </button>
      </view>

    </view>
  </view>
</template>

<script>
import { listInfo, assignNumber as assignApi, getUserList } from '@/api/info.js'
import { listUser, getUser } from '@/api/system/user'
import { addAttendance } from '@/api/system/attendance'

export default {
  data() {
    return {
      // 分配表单
      employeeId: '',
      level: '',
      levelOptions: ['A','B','C'],
      showForm: true,
      displayEmployeeId: '',
      userName: '',
      displayLevel: '',
      displayNumber: '',
      displayRemark: '',
      // 刷新 + 时间
      weekday: '',
      currentTime: '',
      timer: null,
      isClicked: false,
      // 扫码
      scanResult: null,
      // 角色判断
      isBusiness: false,
      // 用户信息
      userInfo: null
    }
  },
  onShow() {
    const roles = uni.getStorageSync('roles') || []
    this.isBusiness = roles.includes('yewuyuan')
    if (this.isBusiness) {
      this.initClock()
      this.loadStoredInfo()
    }
  },
  onUnload() {
    clearInterval(this.timer)
  },
  methods: {
    // —— 业务员逻辑 —— 
    initClock() {
      this.updateTime()
      this.timer = setInterval(this.updateTime, 1000)
    },
    loadStoredInfo() {
      // 获取用户信息
      this.$store.dispatch('GetInfo').then(res => {
        console.log('GetInfo返回结果：', res)
        if (res.code === 200 && res.user) {
          this.userInfo = res.user
          console.log('设置用户信息：', this.userInfo)
          // 延迟一点时间再加载用户详细信息，确保用户信息已经设置完成
          setTimeout(() => {
            this.loadUserInfo()
          }, 100)
        } else {
          console.error('GetInfo返回异常：', res)
          uni.showToast({ title:'获取用户信息失败', icon:'none' })
        }
      }).catch(err => {
        console.error('GetInfo调用失败：', err)
        uni.showToast({ title:'获取用户信息失败', icon:'none' })
      })
    },
    onEmployeeIdInput(e) {
      this.employeeId = e.detail.value
    },
    onLevelChange(e) {
      this.level = this.levelOptions[e.detail.value]
    },
    assignNumber() {
      if (!this.employeeId || !this.level) {
        return uni.showToast({ title:'工号和级别为必填', icon:'none' })
      }
      uni.setStorageSync('employeeId', this.employeeId)

      // 调用分配号码接口
      assignApi({
        userId: this.userInfo.userId,
        employeeId: this.employeeId,
        level: this.level
      }).then(res => {
          if (res.code === 200) {
            uni.showToast({ title:'分配成功', icon:'success' })
            this.showForm = false
          // 更新显示信息
          this.displayEmployeeId = this.employeeId
          this.displayEmployeeId = this.userName
          this.displayLevel = this.level
          this.displayNumber = res.data
          this.displayRemark = '分配成功'
          } else {
          uni.showToast({ title: res.msg || '分配失败', icon:'none' })
          }
      }).catch(err => {
        console.error('分配号码失败：', err)
        uni.showToast({ title:'工号不可为空', icon:'none' })
        })
    },
    loadUserInfo() {
      if (!this.userInfo) {
        console.error('用户信息为空')
        return uni.showToast({ title:'用户信息获取失败', icon:'none' })
      }

      console.log('当前用户信息：', this.userInfo)

      // 优先使用userId查询，如果没有则使用userName
      let queryParams = {}
      if (this.userInfo.userId) {
        queryParams.userId = this.userInfo.userId
        console.log('使用userId查询：', this.userInfo.userId)
      } else if (this.userInfo.userName) {
        queryParams.userName = this.userInfo.userName
        console.log('使用userName查询：', this.userInfo.userName)
      } else {
        console.error('用户信息中既没有userId也没有userName')
        return uni.showToast({ title:'用户信息不完整', icon:'none' })
      }

      queryParams.pageNum = 1
      queryParams.pageSize = 10

      getUserList(queryParams).then(res => {
        console.log('查询结果：', res)
        if (res.code === 200 && res.rows && res.rows.length > 0) {
          const u = res.rows[0]
          console.log('获取到的用户详细信息：', u)
          this.userName = u.userName
          this.displayEmployeeId = u.employeeId
          this.displayLevel = u.level
          this.displayNumber = u.number
          this.displayRemark = u.remark || ''
        } else {
          console.error('查询结果为空或失败：', res)
          // 如果通过列表查询失败，尝试直接通过userId获取单个用户信息
          if (this.userInfo.userId) {
            console.log('尝试通过getUser API获取用户信息：', this.userInfo.userId)
            getUser(this.userInfo.userId).then(userRes => {
              console.log('getUser返回结果：', userRes)
              if (userRes.code === 200 && userRes.data) {
                const u = userRes.data
                console.log('通过getUser获取到的用户信息：', u)
                this.userName = u.userName
                this.displayEmployeeId = u.employeeId
                this.displayLevel = u.level
                this.displayNumber = u.number
                this.displayRemark = u.remark || ''
              } else {
                console.error('getUser返回异常：', userRes)
                uni.showToast({ title:'未找到用户详细信息', icon:'none' })
              }
            }).catch(userErr => {
              console.error('getUser调用失败：', userErr)
              uni.showToast({ title:'获取用户信息失败', icon:'none' })
            })
          } else {
            uni.showToast({ title:'未找到用户详细信息', icon:'none' })
          }
        }
      }).catch(err => {
        console.error('获取用户信息失败：', err)
        uni.showToast({ title:'获取用户信息失败', icon:'none' })
      })
    },
    handleClick() {
      this.isClicked = true
      this.loadUserInfo()
      .finally(() => setTimeout(() => this.isClicked = false, 100))
    },
    updateTime() {
      const now = new Date()
      const w = ['日','一','二','三','四','五','六'][now.getDay()]
      const pad = n=>n<10?'0'+n:n
      this.weekday = `星期${w}`
      this.currentTime = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
    },
    // 扫码功能
    scanQrCode() {
      uni.scanCode({
        onlyFromCamera: true,
        success: async (res) => {
          try {
            const qrData = JSON.parse(res.result)
            console.log('扫码结果：', qrData)
            
            // 判断是否是考勤二维码
            if (qrData.type !== 'kaoqin') {
              uni.showToast({
                title: '无效的考勤二维码',
                icon: 'none'
              })
              return
            }
            
            // 验证日期
            const today = new Date().toISOString().split('T')[0]
            if (qrData.timestamp !== today) {
              uni.showToast({
                title: '二维码已过期',
                icon: 'none'
              })
              return
            }
            
            // 获取用户信息
            const userInfo = uni.getStorageSync('userInfo')
            if (!userInfo || !userInfo.user) {
              uni.showToast({
                title: '未获取到用户信息',
                icon: 'none'
              })
              return
            }
            
            // 显示确认对话框
            uni.showModal({
              title: '考勤确认',
              content: '是否确认打卡？',
              success: async (modalRes) => {
                if (modalRes.confirm) {
                  try {
                    const attendanceData = {
                      userId: userInfo.user.userId,
                      userName: userInfo.user.userName,
                      punchDate: today,
                     
                    }
                    
                    const result = await addAttendance(attendanceData)
                    if (result.code === 200) {
                      uni.showToast({
                        title: '打卡成功',
                        icon: 'success'
                      })
                    } else {
                      uni.showToast({
                        title: result.msg || '打卡失败',
                        icon: 'none'
                      })
                    }
                  } catch (error) {
                    console.error('打卡失败：', error)
                    uni.showToast({
                      title: '打卡失败，请重试',
                      icon: 'none'
                    })
                  }
                }
              }
            })
          } catch (error) {
            console.error('处理扫码结果失败：', error)
            uni.showToast({
              title: '无效的二维码',
              icon: 'none'
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '扫码失败，请重试',
            icon: 'none'
          })
        }
      })
    },
    // 业务员扫码分配号码
    scanAssignQrCode() {
      uni.scanCode({
        onlyFromCamera: true,
        success: async (res) => {
          try {
            const qrData = JSON.parse(res.result)
            console.log('扫码结果：', qrData)
            
            // 判断是否是发码二维码
            if (qrData.type !== 'fama') {
              uni.showToast({
                title: '无效的发码二维码',
                icon: 'none'
              })
              return
            }
            
            // 验证日期
            const today = new Date().toISOString().split('T')[0]
            if (qrData.timestamp !== today) {
              uni.showToast({
                title: '二维码已过期',
                icon: 'none'
              })
              return
            }
            
            // 获取当前业务员信息
            if (!this.userInfo) {
              uni.showToast({
                title: '未获取到用户信息',
                icon: 'none'
              })
              return
            }
            
            // 显示确认对话框
            uni.showModal({
              title: '分配号码',
              content: `是否要为业务员 ${this.userInfo.userName} 分配号码？`,
              success: async (modalRes) => {
                if (modalRes.confirm) {
                  try {
                    // 先分配号码
                    const assignRes = await assignApi({
                      userId: this.userInfo.userId,
                      employeeId: this.userInfo.employeeId,
                      level: '暂无'
                    })
                        
                    if (assignRes.code === 200) {
                      // 分配成功后，调用打卡接口
                      try {
                        const attendanceData = {
                          userId: this.userInfo.userId,
                          userName: this.userInfo.userName,
                          punchDate: today,
                          aa:"业务员打卡"
                        }
                        
                        const attendanceRes = await addAttendance(attendanceData)
                        if (attendanceRes.code === 200) {
                          uni.showToast({
                            title: '分配号码并打卡成功',
                            icon: 'success'
                          })
                        } else {
                          uni.showToast({
                            title: '分配成功，但打卡失败',
                            icon: 'none'
                          })
                        }
                      } catch (attendanceError) {
                        console.error('打卡失败：', attendanceError)
                        uni.showToast({
                          title: '分配成功，但打卡失败',
                          icon: 'none'
                        })
                      }
                      
                      // 刷新显示信息
                      this.loadUserInfo()
                    } else {
                      uni.showToast({
                        title: assignRes.msg || '分配失败',
                        icon: 'none'
                      })
                    }
                  } catch (error) {
                    console.error('分配号码失败：', error)
                    uni.showToast({
                      title: '分配失败，请重试',
                      icon: 'none'
                    })
                  }
                }
              }
            })
          } catch (error) {
            console.error('处理扫码结果失败：', error)
            uni.showToast({
              title: '无效的二维码',
              icon: 'none'
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '扫码失败，请重试',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.page { 
  position: relative; 
  min-height: 100vh; 
}
.container {
  min-height: 100vh;
  background-color: #01b0f1;
  padding-top: 40rpx; /* 减少顶部内边距 */
  padding-bottom: 0rpx; /* 减少底部内边距 */
  align-items: center;
}
/* 标题 */
.title {
  font-size: 48rpx;
  color: #fff;
  font-weight: bold;
  text-align: center;
  margin: 30rpx 0; /* 减少标题下方间距 */
}
/* 分配表单 */
.form-group { display: flex; align-items: center; margin-bottom: 30rpx; }
.form-item, .submit-btn { margin-right: 20rpx; }
.item-id { flex: 3; display: flex; align-items: center; }
.item-level { flex: 2; display: flex; align-items: center; }
.item-btn {
  flex: 1;
  min-width: 160rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #fff;
  color: #01b0f1;
  font-size: 28rpx;
  font-weight: bold;
  border-radius: 10rpx;
  box-shadow: 0 5rpx 15rpx rgba(0,0,0,0.2);
  text-align: center;
}
.label { width: 120rpx; font-size: 28rpx; color: #fff; }
.input, .picker-wrapper {
  flex: 1;
  height: 60rpx;
  padding: 0 20rpx;
  background-color: #fff;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}
.picker { line-height: 60rpx; }
/* 大号号码卡片 */
.number-card {
  width: 80%;
  margin: 10rpx auto; /* 减少上下间距 */
  padding: 10rpx 0; /* 减少内边距 */
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  background-color: #01b0f1; /* 统一背景色 */
}
.day-number { font-size: 400rpx; font-weight: bold; color: #000; }
/* 信息卡片 */
.info-card {
  width: 80%;
  margin: 10rpx auto; /* 减少上下间距 */
  padding: 15rpx; /* 减少内边距 */
  border-radius: 20rpx;
  text-align: center;
  background-color: #01b0f1; /* 统一背景色 */
}
.info-line { 
  font-size: 38rpx; 
  color: #fff; /* 改为白色，在蓝色背景上更清晰 */
  margin-top: 15rpx; /* 减少行间距 */
}
.remarks { 
  font-size: 118rpx; 
  color: #f44; /* 保持红色，突出显示 */
  margin-top: -60rpx; /* 减少与上方号码的间距 */
  display: block;
  text-align: center;
}
/* 刷新 + 时间 */
.bottom-info {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin-top: 20rpx; /* 减少上方间距 */
  padding: 15rpx 0; /* 减少内边距 */
  background-color: #01b0f1; /* 添加背景色 */
}
.circle-container {
  width: 120rpx;
  height: 120rpx;
  margin-right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
.circle-icon {
  width: 100%;
  height: 100%;
  border-radius: 60rpx;
  /* background-color: #fff; */ /* 移除白色背景 */
  box-shadow: 0 5rpx 15rpx rgba(0,0,0,0.2);
  transition: transform 0.2s, opacity 0.2s;
}
.circle-icon.active {
  transform: scale(0.9);
  opacity: 0.7;
}
.time-info {
  display: flex;
  flex-direction: column;
  align-items: center; /* 改为居中对齐 */
  color: #fff; /* 确保文字颜色是白色 */
}
.weekday {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 5rpx; /* 增加一点间距 */
}
.clock {
  font-size: 72rpx;
  font-weight: bold;
}
/* 扫码区域样式 */
.scanner-section {
  text-align: center;
  margin-top: 200rpx;
  padding: 0 30rpx;
}
.scan-btn {
  width: 80%;
  margin: 0 auto;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
}
.result-info {
  margin-top: 40rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}
.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}
.info-item .label {
  color: #666;
  font-size: 28rpx;
}
.info-item .value {
  color: #333;
  font-size: 28rpx;
  font-weight: bold;
}
/* 扫码区域样式 */
.scan-section {
  width: 80%;
  margin: 15rpx auto; /* 减少上下间距 */
  text-align: center;
  background-color: #01b0f1; /* 统一背景色 */
}

.scan-section .scan-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  color: #01b0f1;
  background-color: #fff;
  border-radius: 44rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}
</style>
